package com.insight.modules.system.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.service.*;
import com.yuanqiao.insight.acore.depart.entity.SysDepart;
import com.yuanqiao.insight.common.util.common.LocalCacheUtils;
import com.yuanqiao.insight.common.util.common.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.insight.modules.constant.CommonConstant;
import org.insight.modules.system.entity.*;
import org.insight.modules.system.service.*;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.aspect.annotation.PermissionData;
import com.insight.common.constant.CommonConstant;
import com.insight.common.system.api.ISysBaseAPI;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.system.util.JwtUtil;
import com.insight.common.system.vo.LoginUser;
import com.insight.common.util.CommonUtils;
import com.insight.common.util.ImportExcelUtil;
import com.insight.common.util.PasswordUtil;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.base.service.BaseCommonService;
import com.insight.modules.system.entity.*;
import com.insight.modules.system.model.DepartIdModel;
import com.insight.modules.system.model.SysUserSysDepartModel;
import com.insight.modules.system.service.*;
import com.insight.modules.system.service.impl.SysDepartServiceImpl;
import com.insight.modules.system.util.Base64Util;
import com.insight.modules.system.vo.SysDepartUsersVO;
import com.insight.modules.system.vo.SysUserRoleVO;
import com.insight.modules.system.vo.UserVo;
import com.insight.modules.umpPwdManage.entity.UmpPwdManage;
import com.insight.modules.umpPwdManage.service.IUmpPwdManageService;
import com.insight.modules.util.ChineseCharToEnUtil;
import com.insight.modules.util.ZipEncryUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    private ISysDepartRoleUserService departRoleUserService;

    @Autowired
    private ISysDepartRoleService departRoleService;

    @Autowired
    private RedisUtils redisUtil;

    @Resource
    private BaseCommonService baseCommonService;

    @Autowired
    private IUmpPwdManageService umpPwdManageService;

    @Autowired
    private ZipEncryUtils zipEncryUtils;

    @Autowired
    private ISysRoleService roleService;

    private static final LocalCacheUtils cacheUtils = LocalCacheUtils.getInstance();
    @Value("${jeecg.path.upload}")
    private String upLoadPath;
    //    @Value(value = "${insight.isThreePowers}")

    /**
     * 用户选择组件 专用  根据用户账号或部门分页查询
     *
     * @param departId
     * @param username
     * @return
     */
    @RequestMapping(value = "/queryUserComponentData", method = RequestMethod.GET)
    public Result<IPage<SysUsers>> queryUserComponentData(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "departId", required = false) String departId,
            @RequestParam(name = "realname", required = false) String realname,
            @RequestParam(name = "username", required = false) String username, HttpServletRequest request) {
        IPage<SysUsers> pageList = sysUserDepartService.queryDepartUserPageList(departId, username, realname, pageSize, pageNo, request);
        return Result.OK(pageList);
    }

    /**
     * 获取用户列表数据
     *
     * @param user
     * @param pageNo
     * @param pageSize
     * @return
     */
    @PermissionData(pageComponent = "system/UserList")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysUsers>> queryPageList(SysUsers user, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        QueryWrapper<SysUsers> queryWrapper = new QueryWrapper<>();
        // 外部模拟登陆临时账号，列表不显示 username
        queryWrapper.ne("username", "_reserve_user_external");

        if (StringUtils.isNotEmpty(user.getUsername())) {
            queryWrapper.like("username", user.getUsername());// 设置查询方式为模糊查询
        }
        if (StringUtils.isNotEmpty(user.getRealname())) {
            queryWrapper.like("realname", user.getRealname());// 设置查询方式为模糊查询
        }
        if (user.getSex() != null) {
            queryWrapper.eq("sex", user.getSex());
        }
        if (StringUtils.isNotEmpty(user.getPhone())) {
            queryWrapper.like("phone", user.getPhone());
        }
        if (StringUtils.isNotEmpty(user.getEmail())) {
            queryWrapper.like("email", user.getEmail());
        }
        if (user.getStatus() != null) {
            queryWrapper.eq("status", user.getStatus());
        }
        if (StringUtils.isNotEmpty(user.getId())) {
            queryWrapper.in("id", user.getId().split(","));
        }

        String threePowersKey = com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        int isThreePowers = Integer.parseInt(String.valueOf(cacheUtils.getValueByKey(threePowersKey + "_isEnable")));
        if (isThreePowers == 1) {
            queryWrapper.notIn("username", getThreePowers());
        }
        Page<SysUsers> page = new Page<SysUsers>(pageNo, pageSize);
        IPage<SysUsers> pageList = sysUserService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 通过单位查询用户
     *
     * @param deptId
     * @return
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    public Result<?> queryList(String deptId) {
        List<UserVo> list = sysUserService.list(deptId);
        return Result.OK(list);
    }


    /**
     * 用户管理模块-获取用户列表数据
     *
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "用户管理-分页列表查询")
    @PermissionData(pageComponent = "system/UserList")
    @RequestMapping(value = "/listByCondition", method = RequestMethod.GET)
    public Result<IPage<SysUsers>> queryPageListByCondition(SysUsers user, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUsers>> result = new Result<IPage<SysUsers>>();
//		QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
        QueryWrapper<SysUsers> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(user.getUsername()) && user.getUsername().contains(",")) {
            String[] usernameList = user.getUsername().split(",");
            queryWrapper.in("username", usernameList);
        }

        if (StringUtils.isNotEmpty(user.getUsername()) && !user.getUsername().contains(",")) {
            queryWrapper.like("username", user.getUsername());
        }
        if (user.getSex() != null) {
            queryWrapper.eq("sex", user.getSex());
        }
        if (StringUtils.isNotEmpty(user.getRealname())) {
            queryWrapper.like("realname", user.getRealname());
        }
        if (StringUtils.isNotEmpty(user.getPhone())) {
            queryWrapper.like("phone", user.getPhone());
        }
        if (StringUtils.isNotEmpty(user.getTelephone())) {
            queryWrapper.like("telephone", user.getTelephone());
        }
        if (user.getStatus() != null) {
            queryWrapper.eq("status", user.getStatus());
        }
        String threePowersKey = com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        int isThreePowers = Integer.parseInt(String.valueOf(cacheUtils.getValueByKey(threePowersKey + "_isEnable")));
        if (isThreePowers == 1) {
            List<String> userNames = sysBaseAPI.getUsernameByRoleCode(CommonConstant.ADMIN);
            if (CollUtil.isNotEmpty(userNames)) {
                queryWrapper.notIn("username", userNames);
            }
        }
        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne("username", "_reserve_user_external");
        Page<SysUsers> page = new Page<SysUsers>(pageNo, pageSize);
        IPage<SysUsers> pageList = sysUserService.page(page, queryWrapper);

        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = pageList.getRecords().stream().map(SysUsers::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userIds)) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            pageList.getRecords().forEach(item -> {
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
                item.setIsThreePowers(isThreePowers);
                if (isThreePowers == 1) {
                    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

                    item.setIsThreePowerUser(getThreePowers().contains(item.getUsername()) && !sysUser.getUsername().equals("admin") ? 0 : 1);
                }
            });
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "用户管理-添加用户")
    //@RequiresRoles({"admin"})
    @RequiresPermissions("user:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysUsers> add(@RequestBody JSONObject jsonObject) {
        Result<SysUsers> result = new Result<SysUsers>();
        String selectedRoles = jsonObject.getString("selectedroles");
        String selectedDeparts = jsonObject.getString("selecteddeparts");

        SysUsers user = JSON.parseObject(jsonObject.toJSONString(), SysUsers.class);
        user.setCreateTime(new Date());//设置创建时间
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        sysUserService.addUserWithRole(user, selectedRoles);
        sysUserService.addUserWithDepart(user, selectedDeparts);
        result.success("添加成功！");

        return result;
    }

    /**
     * 后端为指定用户设置密码,重置密码
     * @param args
     */
    public static void main(String[] args) {
        String salt = oConvertUtils.randomGen(8);
        System.out.println("salt ---- " + salt);
        String passwordEncode = PasswordUtil.encrypt("admin", "123456", salt);
        System.out.println("password --- " + passwordEncode);
    }

    @AutoLog(value = "终端激活-添加用户")
    //@RequiresRoles({"admin"})
    //@RequiresPermissions("user:add")
    @RequestMapping(value = "/addByTerminal", method = RequestMethod.POST)
    public Result<SysUsers> addByTerminal(@RequestBody JSONObject jsonObject) {
        Result<SysUsers> result = new Result<SysUsers>();

        SysUsers user = JSON.parseObject(jsonObject.toJSONString(), SysUsers.class);
        user.setCreateTime(new Date());//设置创建时间
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        // 添加用户并绑定默认角色
        String defaultRole = "1724986733645819906";
        sysUserService.addUserWithRole(user, defaultRole);
        String selectedDeparts = jsonObject.getString("selecteddeparts");
        sysUserService.addUserWithDepart(user, selectedDeparts);
        result.success("添加成功！");

        return result;
    }

    @RequestMapping(value = "/getPwd", method = RequestMethod.GET)
    public Result<String> getPwd(SysUsers user) {
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), "123456", user.getSalt());
        return Result.OK(passwordEncode);
    }

    @RequestMapping(value = "/addBatch", method = RequestMethod.GET)
    public Result<SysUsers> addBatch() {
        Result<SysUsers> result = new Result<SysUsers>();

        SysUsers user = null;//
        String selectedRoles = "1430057091121102850";//角色
        String selectedDeparts = "";//部门
        List<SysDepart> sysDeparts = sysDepartService.list();
        for (SysDepart sysDepart : sysDeparts) {
            user = new SysUsers();
            String departName = sysDepart.getDepartName();
            if (-1 != departName.indexOf('(')) {
                departName = departName.substring(0, departName.indexOf('('));
            }
            String userName = ChineseCharToEnUtil.getPinYinHeadChar(departName).toLowerCase();
            SysUsers sysUser = sysUserService.getUserByName(userName);
            if (sysUser != null) {
                userName = userName + new Random().nextInt(9999);
            }
            if (userName.length() > 10 && userName.substring(0, 3).equals("sys")) {
                userName = userName.substring(3);
            }
            user.setUsername(userName);
            user.setRealname(sysDepart.getDepartName());
            user.setPassword("123456");
            //部门
            selectedDeparts = sysDepart.getId();
            addUser(user, selectedRoles, selectedDeparts);
        }

        result.success("添加成功！");

        return result;
    }

    private void addUser(SysUsers user, String selectedRoles, String selectedDeparts) {
        user.setCreateTime(new Date());//设置创建时间
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        sysUserService.addUserWithRole(user, selectedRoles);
        sysUserService.addUserWithDepart(user, selectedDeparts);
    }

    @AutoLog(value = "用户管理-编辑")
    //@RequiresRoles({"admin"})
    @RequiresPermissions(value = {"user:edit","oneClickHelp:user"}, logical = Logical.OR)
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysUsers> edit(@RequestBody JSONObject jsonObject) {
        Result<SysUsers> result = new Result<SysUsers>();
        String selectedroles = jsonObject.getString("selectedroles");
        String roles = selectedroles.replace("[", "").replace("]", "");

        SysUsers sysUser = sysUserService.getById(jsonObject.getString("id"));
        baseCommonService.addLog("编辑用户，id： " + jsonObject.getString("id"), CommonConstant.LOG_TYPE_2, 2);
        if (!StringUtils.equals(sysUser.getAvatar(), jsonObject.getString("avatar"))) {
            boolean b = CommonUtils.deleteFile(Collections.singletonList(sysUser.getAvatar()));
            if (!b) {
                result.error500("删除旧头像失败");
                return result;
            }
        }

        if (sysUser == null) {
            result.error500("未找到对应实体");
        } else {
            SysUsers user = JSON.parseObject(jsonObject.toJSONString(), SysUsers.class);
            user.setUpdateTime(new Date());
            //String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), sysUser.getSalt());
            user.setPassword(sysUser.getPassword());

            String departs = jsonObject.getString("selecteddeparts");
            sysUserService.editUserWithRole(user, roles);
            sysUserService.editUserWithDepart(user, departs);
            boolean b = sysUserService.updateNullPhoneEmail();
            if (!b) {
                result.error500("更新手机号、邮箱空字符串为 null失败");
                return result;
            }
            result.success("修改成功!");
        }

        return result;
    }

    /**
     * 删除用户
     */
    @AutoLog(value = "用户管理-删除")
    //@RequiresRoles({"admin"})
    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        SysUsers user = sysUserService.getOne(new QueryWrapper<SysUsers>().eq("id", id));
        int isThreePowers = Integer.parseInt((String) cacheUtils.getValueByKey(com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers_isEnable"));
        if (isThreePowers == 1) {
            if (getThreePowers().contains(user.getUsername())) {
                return Result.error("三员用户,禁止删除！");
            }
        }

        if (!user.getUsername().equals(CommonConstant.ADMIN)) {
            baseCommonService.addLog("删除用户，id： " + id, CommonConstant.LOG_TYPE_2, 3);
            boolean b = this.sysUserService.deleteUser(id);
            if (!b) {
                return Result.error("删除用户失败");
            }
            return Result.ok("删除用户成功");
        } else {
            return Result.error("管理员用户,禁止删除！");
        }
    }

    /**
     * 批量删除用户
     */
    @AutoLog(value = "用户管理-批量删除")
    //@RequiresRoles({"admin"})
    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SysUsers> userList = sysUserService.list(new QueryWrapper<SysUsers>().in("id", idsList));

        for (SysUsers user : userList) {
            if (user.getUsername().equals(CommonConstant.ADMIN)) {
                return Result.error("当前选中的用户中包含管理员用户，禁止执行删除操作！");
            } else if (getThreePowers().contains(user.getUsername())) {
                return Result.error("三员用户,禁止删除！");
            }
        }
        baseCommonService.addLog("批量删除用户， ids： " + ids, CommonConstant.LOG_TYPE_2, 3);
        boolean b = this.sysUserService.deleteBatchUsers(ids);
        if (!b) {
            return Result.error("批量删除用户失败");
        }
        return Result.ok("批量删除用户成功");
    }

    /**
     * 冻结&解冻用户
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "用户管理-冻结&解冻用户")
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
    public Result<SysUsers> frozenBatch(@RequestBody JSONObject jsonObject) {
        Result<SysUsers> result = new Result<SysUsers>();

        String ids = jsonObject.getString("ids");
        String status = jsonObject.getString("status");
        String[] arr = ids.split(",");
        for (String id : arr) {
            if (oConvertUtils.isNotEmpty(id)) {
                this.sysUserService.update(new SysUsers().setStatus(Integer.parseInt(status)),
                        new UpdateWrapper<SysUsers>().lambda().eq(SysUsers::getId, id));
            }
        }

        result.success("操作成功!");
        return result;

    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<SysUsers> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysUsers> result = new Result<SysUsers>();
        SysUsers sysUser = sysUserService.getById(id);
        if (sysUser == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysUser);
            result.setSuccess(true);
        }
        return result;
    }

    @RequestMapping(value = "/queryUserRole", method = RequestMethod.GET)
    public Result<List<String>> queryUserRole(@RequestParam(name = "userid", required = true) String userid) {
        Result<List<String>> result = new Result<>();
        List<String> list = new ArrayList<String>();
        List<SysUserRole> userRole = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid));
        if (userRole == null || userRole.size() <= 0) {
            result.error500("未找到用户相关角色信息");
        } else {
            for (SysUserRole sysUserRole : userRole) {
                list.add(sysUserRole.getRoleId());
            }
            result.setSuccess(true);
            result.setResult(list);
        }
        return result;
    }

    /**
     * 根据部门选择用户组件新加的接口，带分页功能
     *
     * @param id       部门id
     * @param username 用户名
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/queryUsersByDepIdWithPage", method = RequestMethod.GET)
    public Result<List<SysUsers>> queryUsersByDepIdWithPage(@RequestParam(name = "id") String id,
                                                            @RequestParam(name = "username", required = false) String username,
                                                            @RequestParam(name = "realname", required = false) String realname,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<List<SysUsers>> result = new Result<>();
        //List<SysUser> userList = sysUserDepartService.queryUserByDepId(id);
        SysDepart sysDepart = sysDepartService.getById(id);
        IPage<SysUsers> pageList = sysUserDepartService.queryUserByDepCodeWithPage(sysDepart.getOrgCode(), username, realname, pageNo,pageSize);
        if (pageList != null){
            List<SysUsers> userList = pageList.getRecords();
            //批量查询用户的所属部门
            //step.1 先拿到全部的 useids
            //step.2 通过 useids，一次性查询用户的所属部门名字
            List<String> userIds = userList.stream().map(SysUsers::getId).collect(Collectors.toList());
            if (userIds != null && userIds.size() > 0) {
                Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
                userList.forEach(item -> {
                    //TODO 临时借用这个字段用于页面展示
                    item.setOrgCodeTxt(useDepNames.get(item.getId()));
                });
            }
        }

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 校验用户账号是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/checkOnlyUser", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyUser(SysUsers sysUser) {
        Result<Boolean> result = new Result<>();
        //如果此参数为false则程序发生异常
        result.setResult(true);

        //通过传入信息查询新的用户信息
        SysUsers user = sysUserService.getOne(new QueryWrapper<SysUsers>(sysUser));
        if (user != null) {
            result.setSuccess(false);
            result.setMessage("用户账号已存在");
            return result;
        }


        result.setSuccess(true);
        return result;
    }

    /**
     * 修改密码
     */
    @AutoLog(value = "用户管理-重置密码")
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
    public Result<?> changePassword(@RequestBody SysUsers sysUser) {
        int judge = judge(sysUser.getPassword());
        if (judge == 1) {
            return Result.error("密码长度不正确，修改失败");
        } else if (judge == 2) {
            return Result.error("密码中不存在大写字母，修改失败");
        } else if (judge == 3) {
            return Result.error("密码中不存在小写字母，修改失败");
        } else if (judge == 4) {
            return Result.error("密码中不存在数字，修改失败");
        } else if (judge == 5) {
            return Result.error("密码中不存在特殊字符，修改失败");
        }

        SysUsers u = this.sysUserService.getOne(new LambdaQueryWrapper<SysUsers>().eq(SysUsers::getUsername, sysUser.getUsername()));
        if (u == null) {
            return Result.error("用户不存在！");
        }
        sysUser.setId(u.getId());
        return sysUserService.changePassword(sysUser);
    }


    // 判断密码规则
    public int judge(String password) {
        Pattern p = Pattern.compile("[A-Z]+");
        Pattern q = Pattern.compile("[a-z]+");
        Pattern r = Pattern.compile("[0-9]+");
        Pattern s = Pattern.compile("\\p{Punct}+");

        List<UmpPwdManage> list = umpPwdManageService.list();
        for (UmpPwdManage umpPwdManage : list) {
            if (password.trim().length() < Integer.parseInt(umpPwdManage.getPwdMin())) {
                return 1; // 长度超了
            }

            if (umpPwdManage.getCapitalize() == 1) { // 大写
                Matcher m1 = p.matcher(password); //判断是否含有大写字符
                if (!m1.find()) {
                    return 2; // 密码中不存在大写字母
                }


            }

            if (umpPwdManage.getLowercase() == 1) {
                Matcher m2 = q.matcher(password); // 大小写
                if (!m2.find()) {
                    return 3; // 密码中不存在小写字母
                }
            }

            if (umpPwdManage.getHasNum() == 1) {
                Matcher m3 = r.matcher(password); // 数字
                if (!m3.find()) {
                    return 4; // 密码中不存在数字
                }
            }

            if (umpPwdManage.getSpecial() == 1) {
                Matcher m4 = s.matcher(password);//判断是否含有特殊字符
                if (!m4.find()) {
                    return 5; // 密码中不存在特殊字符
                }
            }
        }
        return 6;

    }


    /**
     * 查询指定用户和部门关联的数据
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/userDepartList", method = RequestMethod.GET)
    public Result<List<DepartIdModel>> getUserDepartsList(@RequestParam(name = "userId", required = true) String userId) {
        Result<List<DepartIdModel>> result = new Result<>();

        List<DepartIdModel> depIdModelList = this.sysUserDepartService.queryDepartIdsOfUser(userId);
        if (depIdModelList != null && depIdModelList.size() > 0) {
            result.setSuccess(true);
            result.setMessage("查找成功");
            result.setResult(depIdModelList);
        } else {
            result.setSuccess(false);
            result.setMessage("查找失败");
        }
        return result;


    }

    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
     *
     * @return
     */
    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
    public Result<String> generateUserId() {
        Result<String> result = new Result<>();
        String userId = UUID.randomUUID().toString().replace("-", "");
        result.setSuccess(true);
        result.setResult(userId);
        return result;
    }

    /**
     * 根据部门id查询用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryUserByDepId", method = RequestMethod.GET)
    public Result<List<SysUsers>> queryUserByDepId(@RequestParam(name = "id", required = true) String id,
                                                   @RequestParam(name = "realname", required = false) String realname,
                                                   @RequestParam(name = "delflag", required = false) Integer delflag) {
        Result<List<SysUsers>> result = new Result<>();
        //List<SysUser> userList = sysUserDepartService.queryUserByDepId(id);
        SysDepart sysDepart = sysDepartService.getById(id);
        List<SysUsers> userList = sysUserDepartService.queryUserByDepCode(sysDepart.getOrgCode(), realname, delflag);
        String threePowersKey = com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        int isThreePowers = Integer.parseInt(String.valueOf(cacheUtils.getValueByKey(threePowersKey + "_isEnable")));
        if (isThreePowers == 1) {
            //获取登录用户信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<String> userNames = sysBaseAPI.getUsernameByRoleCode(org.jeecg.modules.constant.CommonConstant.ADMIN);
            if (!org.jeecg.modules.constant.CommonConstant.ADMIN.equals(sysUser.getUsername()) && CollUtil.isNotEmpty(userNames)) {
                userList = userList.stream()
                        .filter(item -> userNames.stream().noneMatch(un -> un.equals(item.getUsername())))
                        .collect(Collectors.toList());
            }
        }
        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = userList.stream().map(SysUsers::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            userList.forEach(item -> {
                //TODO 临时借用这个字段用于页面展示
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }


        result.setSuccess(true);
        result.setResult(userList);
        return result;

    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysUser
     */
    //@AutoLog(value = "用户管理-导出")
    @RequestMapping(value = "/exportXls")
    public void exportXls(SysUsers sysUser, HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        SysUsers tmpUser = new SysUsers();
        QueryWrapper<SysUsers> queryWrapper = QueryGenerator.initQueryWrapper(tmpUser, request.getParameterMap());
        // 外部模拟登陆临时账号，列表不显示 username
        queryWrapper.ne("username", "_reserve_user_external");
        if (StringUtils.isNotEmpty(sysUser.getUsername())) {
            queryWrapper.like("username", sysUser.getUsername());// 设置查询方式为模糊查询
        }
        if (StringUtils.isNotEmpty(sysUser.getRealname())) {
            queryWrapper.like("realname", sysUser.getRealname());// 设置查询方式为模糊查询
        }
        if (sysUser.getSex() != null) {
            queryWrapper.eq("sex", sysUser.getSex());// 设置查询方式为模糊查询
        }
        if (StringUtils.isNotEmpty(sysUser.getTelephone())) {
            queryWrapper.like("telephone", sysUser.getTelephone());
        }
        if (sysUser.getStatus() != null) {
            queryWrapper.eq("status", sysUser.getStatus());
        }
        String selections = request.getParameter("selections");
        if (!oConvertUtils.isEmpty(selections)) {
            queryWrapper.in("id", selections.split(","));
        }
        List<SysUsers> pageList = sysUserService.list(queryWrapper);

        List<String> userIds = pageList.stream().map(SysUsers::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            pageList.forEach(item -> {
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }

        UmpPwdManage zip = umpPwdManageService.getZip();
        String fileName = umpPwdManageService.exportXlsRename("用户管理");
        zipEncryUtils.zipPwd(response, SysUsers.class, fileName, zip.getZipPwd(), zip.getIsEncry(), pageList);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "用户管理-导入")
    //@RequiresRoles({"admin"})
    //@RequiresPermissions("user:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest != null ? multipartRequest.getFileMap() : null;
        List<String> errorMessage = new ArrayList<>();
        int successLines = 0, errorLines = 0;
        if (fileMap == null || fileMap.isEmpty()) {
            errorMessage.add("未找到上传的文件");
            return ImportExcelUtil.imporReturnRes(errorLines + 1, successLines, errorMessage);
        }
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();
            if (file == null) {
                continue;
            }
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SysUsers> listSysUsers = ExcelImportUtil.importExcel(file.getInputStream(), SysUsers.class, params);
                if (listSysUsers == null) {
                    continue;
                }
                for (int i = 0; i < listSysUsers.size(); i++) {
                    SysUsers sysUserExcel = listSysUsers.get(i);
                    if (sysUserExcel == null) {
                        errorLines++;
                        continue;
                    }
                    if (StringUtils.isBlank(sysUserExcel.getPassword())) {
                        sysUserExcel.setPassword("123456");
                    }
                    String salt = oConvertUtils.randomGen(8);
                    sysUserExcel.setSalt(salt);
                    String passwordEncode = PasswordUtil.encrypt(sysUserExcel.getUsername(), sysUserExcel.getPassword(), salt);
                    sysUserExcel.setPassword(passwordEncode);
                    try {
                        if (sysUserService == null) {
                            throw new IllegalStateException("用户服务不可用");
                        }
                        QueryWrapper<SysUsers> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(SysUsers::getUsername, sysUserExcel.getUsername());
                        int count = sysUserService.count(queryWrapper);
                        if (count > 0) {
                            throw new IllegalArgumentException(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USERNAME);
                        }
                        sysUserService.save(sysUserExcel);
                        successLines++;
                    } catch (Exception e) {
                        errorLines++;
                        String message = e.getMessage();
                        int lineNumber = i + 1;
                        if (message != null && message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_USERNAME)) {
                            errorMessage.add("第 " + lineNumber + " 行：用户名已经存在，忽略导入。");
                        } else if (message != null && message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_WORK_NO)) {
                            errorMessage.add("第 " + lineNumber + " 行：工号已经存在，忽略导入。");
                        } else if (message != null && message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_PHONE)) {
                            errorMessage.add("第 " + lineNumber + " 行：手机号已经存在，忽略导入。");
                        } else if (message != null && message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_USER_EMAIL)) {
                            errorMessage.add("第 " + lineNumber + " 行：电子邮件已经存在，忽略导入。");
                        } else {
                            errorMessage.add("第 " + lineNumber + " 行：未知错误，忽略导入");
                            log.error(e.getMessage(), e);
                        }
                    }
                    String departIds = sysUserExcel.getDepartIds();
                    if (StringUtils.isNotBlank(departIds)) {
                        String userId = sysUserExcel.getId();
                        if (userId != null) {
                            String[] departIdArray = departIds.split(",");
                            List<SysUserDepart> userDepartList = new ArrayList<>(departIdArray.length);
                            for (String departId : departIdArray) {
                                if (departId != null && !departId.trim().isEmpty()) {
                                    userDepartList.add(new SysUserDepart(userId, departId.trim()));
                                }
                            }
                            if (!userDepartList.isEmpty() && sysUserDepartService != null) {
                                sysUserDepartService.saveBatch(userDepartList);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                errorMessage.add("发生异常：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
                log.error(e.getMessage(), e);
            } finally {
                try {
                    file.getInputStream().close();
                } catch (Exception e) {
                    log.error("关闭输入流异常", e);
                }
            }
        }
        return ImportExcelUtil.imporReturnRes(errorLines, successLines, errorMessage);
    }

    /**
     * @param userIds
     * @return
     * @功能：根据id 批量查询
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public Result<Collection<SysUsers>> queryByIds(@RequestParam String userIds) {
        Result<Collection<SysUsers>> result = new Result<>();
        String[] userId = userIds.split(",");
        Collection<String> idList = Arrays.asList(userId);
        Collection<SysUsers> userRole = sysUserService.listByIds(idList);
        result.setSuccess(true);
        result.setResult(userRole);
        return result;
    }

    /**
     * 首页用户重置密码
     */
    //@RequiresRoles({"admin"})
    @AutoLog(value = "用户管理-修改密码", logType = CommonConstant.LOG_TYPE_3)
    @RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
    public Result<?> changPassword(@RequestBody JSONObject json) {
        String username = json.getString("username");
        String oldpassword = json.getString("oldpassword");
        String password = json.getString("password");
        String confirmpassword = json.getString("confirmpassword");

        if (oldpassword.equals(password)) {
            return Result.error("新密码不能与旧密码相同！");
        }
        int judge = judge(password);
        if (judge == 1) {
            return Result.error("密码长度不正确，修改失败");
        } else if (judge == 2) {
            return Result.error("密码中不存在大写字母，修改失败");
        } else if (judge == 3) {
            return Result.error("密码中不存在小写字母，修改失败");
        } else if (judge == 4) {
            return Result.error("密码中不存在数字，修改失败");
        } else if (judge == 5) {
            return Result.error("密码中不存在特殊字符，修改失败");
        }
        json.put("oldpassword", "*********");
        json.put("password", "*********");
        json.put("confirmpassword", "*********");
        return sysUserService.resetPassword(username, oldpassword, password, confirmpassword);
    }

    @AutoLog(value = "角色管理-用户")
    @RequestMapping(value = "/userRoleList", method = RequestMethod.GET)
    public Result<IPage<SysUsers>> userRoleList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUsers>> result = new Result<IPage<SysUsers>>();
        Page<SysUsers> page = new Page<SysUsers>(pageNo, pageSize);
        String roleId = req.getParameter("roleId");
        String username = req.getParameter("username");
        String realname = req.getParameter("realname");


        IPage<SysUsers> pageList = sysUserService.getUserByRoleId(page, roleId, username, realname);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    @RequestMapping(value = "/queryUsersRolesList", method = RequestMethod.GET)
    public Result<IPage<SysUsers>> queryUsersRolesList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        String roleId = req.getParameter("roleId");
        if (StringUtils.isNotEmpty(roleId)) {
            return userRoleList(pageNo, pageSize, req);
        } else {
            String username = req.getParameter("username");
            String realname = req.getParameter("realname");
            SysUsers user = new SysUsers();
            user.setUsername(username);
            user.setRealname(realname);
            return queryPageList(user, pageNo, pageSize);
        }
    }

    /**
     * 给指定角色添加用户
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @AutoLog(value = "角色管理-用户授权")
    @RequestMapping(value = "/addSysUserRole", method = RequestMethod.POST)
    public Result<String> addSysUserRole(@RequestBody SysUserRoleVO sysUserRoleVO) {
        Result<String> result = new Result<String>();
        sysUserRoleService.grantRole(sysUserRoleVO);
        result.setMessage("添加成功!");
        result.setSuccess(true);
        return result;
    }

    /**
     * 删除指定角色的用户关系
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserRole", method = RequestMethod.DELETE)
    public Result<SysUserRole> deleteUserRole(@RequestParam(name = "roleId") String roleId,
                                              @RequestParam(name = "userId", required = true) String userId) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        try {
            if (roleId == null || userId == null) {
                result.error500("角色ID或用户ID不能为空");
                return result;
            }
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).eq("user_id", userId);
            if (sysUserRoleService == null) {
                result.error500("服务不可用");
                return result;
            }
            sysUserRoleService.remove(queryWrapper);
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定角色的用户关系
     *
     * @param
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserRoleBatch", method = RequestMethod.DELETE)
    public Result<SysUserRole> deleteUserRoleBatch(
            @RequestParam(name = "roleId") String roleId,
            @RequestParam(name = "userIds", required = true) String userIds) {
        Result<SysUserRole> result = new Result<SysUserRole>();
        try {
            if (roleId == null || userIds == null) {
                result.error500("角色ID或用户ID不能为空");
                return result;
            }
            QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<SysUserRole>();
            queryWrapper.eq("role_id", roleId).in("user_id", Arrays.asList(userIds.split(",")));
            if (sysUserRoleService == null) {
                result.error500("服务不可用");
                return result;
            }
            sysUserRoleService.remove(queryWrapper);
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 部门用户列表
     */
    @RequestMapping(value = "/departUserList", method = RequestMethod.GET)
    public Result<IPage<SysUsers>> departUserList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<SysUsers>> result = new Result<IPage<SysUsers>>();
        Page<SysUsers> page = new Page<SysUsers>(pageNo, pageSize);
        String depId = req.getParameter("depId");
        String username = req.getParameter("username");
        //根据部门ID查询,当前和下级所有的部门IDS
        List<String> subDepids = new ArrayList<>();
        //部门id为空时，查询我的部门下所有用户
        if (oConvertUtils.isEmpty(depId)) {
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            int userIdentity = user.getUserIdentity() != null ? user.getUserIdentity() : CommonConstant.USER_IDENTITY_1;
            if (oConvertUtils.isNotEmpty(userIdentity) && userIdentity == CommonConstant.USER_IDENTITY_2) {
                subDepids = sysDepartService.getMySubDepIdsByDepId(user.getDepartIds());
            }
        } else {
            subDepids = sysDepartService.getSubDepIdsByDepId(depId);
        }
        if (subDepids != null && subDepids.size() > 0) {
            IPage<SysUsers> pageList = sysUserService.getUserByDepIds(page, subDepids, username);
            //批量查询用户的所属部门
            //step.1 先拿到全部的 useids
            //step.2 通过 useids，一次性查询用户的所属部门名字
            List<String> userIds = pageList.getRecords().stream().map(SysUsers::getId).collect(Collectors.toList());
            if (userIds != null && userIds.size() > 0) {
                Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
                pageList.getRecords().forEach(item -> {
                    //批量查询用户的所属部门
                    item.setOrgCode(useDepNames.get(item.getId()));
                });
            }
            result.setSuccess(true);
            result.setResult(pageList);
        } else {
            result.setSuccess(true);
            result.setResult(null);
        }
        return result;
    }


    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 若某个用户包含多个部门，则会显示多条记录，可自行处理成单条记录
     */
    @GetMapping("/queryByOrgCode")
    public Result<?> queryByDepartId(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode") String orgCode,
            SysUsers userParams
    ) {
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, new Page(pageNo, pageSize));
        return Result.ok(pageList);
    }

    /**
     * 根据 orgCode 查询用户，包括子部门下的用户
     * 针对通讯录模块做的接口，将多个部门的用户合并成一条记录，并转成对前端友好的格式
     */
    @GetMapping("/queryByOrgCodeForAddressList")
    public Result<?> queryByOrgCodeForAddressList(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "orgCode", required = false) String orgCode,
            SysUsers userParams
    ) {
        IPage page = new Page(pageNo, pageSize);
        IPage<SysUserSysDepartModel> pageList = sysUserService.queryUserByOrgCode(orgCode, userParams, page);
        List<SysUserSysDepartModel> list = pageList.getRecords();

        // 记录所有出现过的 user, key = userId
        Map<String, JSONObject> hasUser = new HashMap<>(list.size());

        JSONArray resultJson = new JSONArray(list.size());

        for (SysUserSysDepartModel item : list) {
            String userId = item.getId();
            // userId
            JSONObject getModel = hasUser.get(userId);
            // 之前已存在过该用户，直接合并数据
            if (getModel != null) {
                String departName = getModel.get("departName").toString();
                getModel.put("departName", (departName + " | " + item.getDepartName()));
            } else {
                // 将用户对象转换为json格式，并将部门信息合并到 json 中
                JSONObject json = JSON.parseObject(JSON.toJSONString(item));
                json.remove("id");
                json.put("userId", userId);
                json.put("departId", item.getDepartId());
                json.put("departName", item.getDepartName());
//                json.put("avatar", item.getSysUser().getAvatar());
                resultJson.add(json);
                hasUser.put(userId, json);
            }
        }

        IPage<JSONObject> result = new Page<>(pageNo, pageSize, pageList.getTotal());
        result.setRecords(resultJson.toJavaList(JSONObject.class));
        return Result.ok(result);
    }

    /**
     * 给指定部门添加对应的用户
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/editSysDepartWithUser", method = RequestMethod.POST)
    public Result<String> editSysDepartWithUser(@RequestBody SysDepartUsersVO sysDepartUsersVO) {
        Result<String> result = new Result<String>();
        try {
            if (sysDepartUsersVO == null || sysDepartUsersVO.getDepId() == null || sysDepartUsersVO.getUserIdList() == null) {
                result.setSuccess(false);
                result.setMessage("请求参数不能为空");
                return result;
            }
            String sysDepId = sysDepartUsersVO.getDepId();
            if (sysUserDepartService == null) {
                result.setSuccess(false);
                result.setMessage("服务不可用");
                return result;
            }
            for (String sysUserId : sysDepartUsersVO.getUserIdList()) {
                if (sysUserId != null) {
                    SysUserDepart sysUserDepart = new SysUserDepart(null, sysUserId, sysDepId);
                    QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
                    queryWrapper.eq("dep_id", sysDepId).eq("user_id", sysUserId);
                    SysUserDepart one = sysUserDepartService.getOne(queryWrapper);
                    if (one == null) {
                        sysUserDepartService.save(sysUserDepart);
                    }
                }
            }
            result.setMessage("添加成功!");
            result.setSuccess(true);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setMessage("出错了: " + e.getMessage());
            return result;
        }
    }

    /**
     * 删除指定机构的用户关系
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserInDepart", method = RequestMethod.DELETE)
    public Result<SysUserDepart> deleteUserInDepart(@RequestParam(name = "depId") String depId,
                                                    @RequestParam(name = "userId", required = true) String userId) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        try {
            if (depId == null || userId == null) {
                result.error500("部门ID或用户ID不能为空");
                return result;
            }
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).eq("user_id", userId);
            if (sysUserDepartService == null || departRoleService == null || departRoleUserService == null) {
                result.error500("服务不可用");
                return result;
            }
            boolean b = sysUserDepartService.remove(queryWrapper);
            if (b) {
                List<SysDepartRole> sysDepartRoleList = departRoleService.list(new QueryWrapper<SysDepartRole>().eq("depart_id", depId));
                if (sysDepartRoleList != null && !sysDepartRoleList.isEmpty()) {
                    List<String> roleIds = sysDepartRoleList.stream()
                            .map(SysDepartRole::getId)
                            .filter(id -> id != null)
                            .collect(Collectors.toList());
                    if (!roleIds.isEmpty()) {
                        QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
                        query.eq("user_id", userId).in("drole_id", roleIds);
                        departRoleUserService.remove(query);
                    }
                }
                result.success("删除成功!");
            } else {
                result.error500("当前选中部门与用户无关联关系!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 批量删除指定机构的用户关系
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteUserInDepartBatch", method = RequestMethod.DELETE)
    public Result<SysUserDepart> deleteUserInDepartBatch(
            @RequestParam(name = "depId") String depId,
            @RequestParam(name = "userIds", required = true) String userIds) {
        Result<SysUserDepart> result = new Result<SysUserDepart>();
        try {
            if (depId == null || userIds == null || userIds.trim().isEmpty()) {
                result.error500("部门ID或用户ID不能为空");
                return result;
            }
            if (sysUserDepartService == null || departRoleUserService == null) {
                result.error500("服务不可用");
                return result;
            }
            QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<SysUserDepart>();
            queryWrapper.eq("dep_id", depId).in("user_id", Arrays.asList(userIds.split(",")));
            boolean b = sysUserDepartService.remove(queryWrapper);
            if (b) {
                departRoleUserService.removeDeptRoleUser(Arrays.asList(userIds.split(",")), depId);
            }
            result.success("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("删除失败！");
        }
        return result;
    }

    /**
     * 查询当前用户的所有部门/当前部门编码
     *
     * @return
     */
    @RequestMapping(value = "/getCurrentUserDeparts", method = RequestMethod.GET)
    public Result<Map<String, Object>> getCurrentUserDeparts() {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> list = this.sysDepartService.queryUserDeparts(sysUser.getId());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", list);
        map.put("orgCode", sysUser.getOrgCode());
        result.setSuccess(true);
        result.setResult(map);
        return result;
    }


    /**
     * 用户注册接口
     *
     * @param jsonObject
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result<JSONObject> userRegister(@RequestBody JSONObject jsonObject, SysUsers user) {
        Result<JSONObject> result = new Result<JSONObject>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        Object code = redisUtil.get(phone);
        String username = jsonObject.getString("username");
        //未设置用户名，则用手机号作为用户名
        if (oConvertUtils.isEmpty(username)) {
            username = phone;
        }
        //未设置密码，则随机生成一个密码
        String password = jsonObject.getString("password");
        if (oConvertUtils.isEmpty(password)) {
            password = RandomUtil.randomString(8);
        }
        String email = jsonObject.getString("email");
        SysUsers sysUser1 = sysUserService.getUserByName(username);
        if (sysUser1 != null) {
            result.setMessage("用户名已注册");
            result.setSuccess(false);
            return result;
        }
        SysUsers sysUser2 = sysUserService.getUserByPhone(phone);
        if (sysUser2 != null) {
            result.setMessage("该手机号已注册");
            result.setSuccess(false);
            return result;
        }

        if (oConvertUtils.isNotEmpty(email)) {
            SysUsers sysUser3 = sysUserService.getUserByEmail(email);
            if (sysUser3 != null) {
                result.setMessage("邮箱已被注册");
                result.setSuccess(false);
                return result;
            }
        }
        if (null == code) {
            result.setMessage("手机验证码失效，请重新获取");
            result.setSuccess(false);
            return result;
        }
        if (!smscode.equals(code.toString())) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        user.setCreateTime(new Date());// 设置创建时间
        String salt = oConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(username, password, salt);
        user.setSalt(salt);
        user.setUsername(username);
        user.setRealname(username);
        user.setPassword(passwordEncode);
        user.setEmail(email);
        user.setPhone(phone);
        user.setStatus(CommonConstant.USER_UNFREEZE);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        user.setActivitiSync(CommonConstant.ACT_SYNC_0);
        sysUserService.addUserWithRole(user, "ee8626f80f7c2619917b6236f3a7f02b");//默认临时角色 test
        result.success("注册成功");

        return result;
    }

    /**
     * 根据用户名或手机号查询用户信息
     *
     * @param
     * @return
     */
    @GetMapping("/querySysUser")
    public Result<Map<String, Object>> querySysUser(SysUsers sysUser) {
        String phone = sysUser.getPhone();
        String username = sysUser.getUsername();
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        if (oConvertUtils.isNotEmpty(phone)) {
            SysUsers user = sysUserService.getUserByPhone(phone);
            if (user != null) {
                map.put("username", user.getUsername());
                map.put("phone", user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        if (oConvertUtils.isNotEmpty(username)) {
            SysUsers user = sysUserService.getUserByName(username);
            if (user != null) {
                map.put("username", user.getUsername());
                map.put("phone", user.getPhone());
                result.setSuccess(true);
                result.setResult(map);
                return result;
            }
        }
        result.setSuccess(false);
        result.setMessage("验证失败");
        return result;
    }

    /**
     * 用户手机号验证
     */
    @PostMapping("/phoneVerification")
    public Result<Map<String, String>> phoneVerification(@RequestBody JSONObject jsonObject) {
        Result<Map<String, String>> result = new Result<Map<String, String>>();
        String phone = jsonObject.getString("phone");
        String smscode = jsonObject.getString("smscode");
        Object code = redisUtil.get(phone);
        if (!smscode.equals(code)) {
            result.setMessage("手机验证码错误");
            result.setSuccess(false);
            return result;
        }
        //设置有效时间
        redisUtil.set(phone, smscode, 600);
        //新增查询用户名
        LambdaQueryWrapper<SysUsers> query = new LambdaQueryWrapper<>();
        query.eq(SysUsers::getPhone, phone);
        SysUsers user = sysUserService.getOne(query);
        Map<String, String> map = new HashMap<>();
        map.put("smscode", smscode);
        map.put("username", user.getUsername());
        result.setResult(map);
        result.setSuccess(true);
        return result;
    }

    /**
     * 用户更改密码
     */
    @GetMapping("/passwordChange")
    public Result<SysUsers> passwordChange(@RequestParam(name = "username") String username,
                                           @RequestParam(name = "password") String password,
                                           @RequestParam(name = "smscode") String smscode,
                                           @RequestParam(name = "phone") String phone) {
        Result<SysUsers> result = new Result<SysUsers>();
        if (oConvertUtils.isEmpty(username) || oConvertUtils.isEmpty(password) || oConvertUtils.isEmpty(smscode) || oConvertUtils.isEmpty(phone)) {
            result.setMessage("重置密码失败！");
            result.setSuccess(false);
            return result;
        }

        SysUsers sysUser = new SysUsers();
        Object object = redisUtil.get(phone);
        if (null == object) {
            result.setMessage("短信验证码失效！");
            result.setSuccess(false);
            return result;
        }
        if (!smscode.equals(object)) {
            result.setMessage("短信验证码不匹配！");
            result.setSuccess(false);
            return result;
        }
        sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUsers>().eq(SysUsers::getUsername, username).eq(SysUsers::getPhone, phone));
        if (sysUser == null) {
            result.setMessage("未找到用户！");
            result.setSuccess(false);
            return result;
        } else {
            String salt = oConvertUtils.randomGen(8);
            sysUser.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
            sysUser.setPassword(passwordEncode);
            this.sysUserService.updateById(sysUser);
            result.setSuccess(true);
            result.setMessage("密码重置完成！");
            return result;
        }
    }

    @GetMapping("/getUserAvatar")
    public Result<?> getUserAvatar() {
        //获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUsers user = sysUserService.getById(sysUser.getId());
        return Result.OK(user.getAvatar());
    }

    /**
     * 根据TOKEN获取用户的部分信息（返回的数据是可供表单设计器使用的数据）
     *
     * @return
     */
    @GetMapping("/getUserSectionInfoByToken")
    public Result<?> getUserSectionInfoByToken(HttpServletRequest request, @RequestParam(name = "token", required = false) String token) {

        String username = null;
        // 如果没有传递token，就从header中获取token并获取用户信息
        if (oConvertUtils.isEmpty(token)) {
            username = JwtUtil.getUserNameByToken(request);
        } else {
            username = JwtUtil.getUsername(token);
        }

        log.info(" ------ 通过令牌获取部分用户信息，当前用户： " + username);

        // 根据用户名查询用户信息
        SysUsers sysUser = sysUserService.getUserByName(username);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sysUserId", sysUser.getId());
        map.put("sysUserCode", sysUser.getUsername()); // 当前登录用户登录账号
        map.put("sysUserName", sysUser.getRealname()); // 当前登录用户真实名称
        map.put("sysOrgCode", sysUser.getOrgCode()); // 当前登录用户部门编号

        log.info(" ------ 通过令牌获取部分用户信息，已获取的用户信息： " + map);

        return Result.ok(map);

    }

    /**
     * 【APP端接口】获取用户列表  根据用户名和真实名 模糊匹配
     *
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/appUserList")
    public Result<?> appUserList(@RequestParam(name = "keyword", required = false) String keyword,
                                 @RequestParam(name = "username", required = false) String username,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 @RequestParam(name = "syncFlow", required = false) String syncFlow) {

        //TODO 从查询效率上将不要用mp的封装的page分页查询 建议自己写分页语句
        LambdaQueryWrapper<SysUsers> query = new LambdaQueryWrapper<SysUsers>();
        if (oConvertUtils.isNotEmpty(syncFlow)) {
            query.eq(SysUsers::getActivitiSync, CommonConstant.ACT_SYNC_1);
        }
        query.eq(SysUsers::getDelFlag, CommonConstant.DEL_FLAG_0);
        if (oConvertUtils.isNotEmpty(username)) {
            if (username.contains(",")) {
                query.in(SysUsers::getUsername, username.split(","));
            } else {
                query.eq(SysUsers::getUsername, username);
            }
        } else {
            query.and(i -> i.like(SysUsers::getUsername, keyword).or().like(SysUsers::getRealname, keyword));
        }
        Page<SysUsers> page = new Page<>(pageNo, pageSize);
        IPage<SysUsers> res = this.sysUserService.page(page, query);
        return Result.ok(res);

    }

    /**
     * 获取被逻辑删除的用户列表，无分页
     *
     * @return logicDeletedUserList
     */
    @AutoLog(value = "用户管理-回收站")
    @GetMapping("/recycleBin")
    public Result getRecycleBin() {
        List<SysUsers> logicDeletedUserList = sysUserService.queryLogicDeleted();
        if (logicDeletedUserList.size() > 0) {
            // 批量查询用户的所属部门
            // step.1 先拿到全部的 userIds
            List<String> userIds = logicDeletedUserList.stream().map(SysUsers::getId).collect(Collectors.toList());
            // step.2 通过 userIds，一次性查询用户的所属部门名字
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            logicDeletedUserList.forEach(item -> item.setOrgCode(useDepNames.get(item.getId())));
        }
        return Result.ok(logicDeletedUserList);
    }

    /**
     * 还原被逻辑删除的用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/putRecycleBin", method = RequestMethod.PUT)
    public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        String userIds = jsonObject.getString("userIds");
        if (StringUtils.isNotBlank(userIds)) {
            SysUsers updateUser = new SysUsers();
            updateUser.setUpdateBy(JwtUtil.getUserNameByToken(request));
            updateUser.setUpdateTime(new Date());
            boolean b = sysUserService.revertLogicDeleted(Arrays.asList(userIds.split(",")), updateUser);
            if (!b) {
                return Result.error("还原失败");
            }
        }
        return Result.ok("还原成功");
    }

    /**
     * 彻底删除用户
     *
     * @param userIds 被删除的用户ID，多个id用半角逗号分割
     * @return
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.DELETE)
    public Result deleteRecycleBin(@RequestParam("userIds") String userIds) {
        if (StringUtils.isNotBlank(userIds)) {
            boolean b = sysUserService.removeLogicDeleted(Arrays.asList(userIds.split(",")));
            if (!b) {
                return Result.error("删除失败");
            }
        }
        return Result.ok("删除成功");
    }


    /**
     * 移动端修改用户信息
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/appEdit", method = RequestMethod.PUT)
    public Result<SysUsers> appEdit(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        Result<SysUsers> result = new Result<SysUsers>();

        String username = JwtUtil.getUserNameByToken(request);
        SysUsers sysUser = sysUserService.getUserByName(username);
        baseCommonService.addLog("移动端编辑用户，id： " + jsonObject.getString("id"), CommonConstant.LOG_TYPE_2, 2);
        String realname = jsonObject.getString("realname");
        String avatar = jsonObject.getString("avatar");
        String sex = jsonObject.getString("sex");
        String phone = jsonObject.getString("phone");
        String email = jsonObject.getString("email");
        Date birthday = jsonObject.getDate("birthday");
        SysUsers userPhone = sysUserService.getUserByPhone(phone);
        if (sysUser == null) {
            result.error500("未找到对应用户!");
        } else {
            if (userPhone != null) {
                String userPhonename = userPhone.getUsername();
                if (!userPhonename.equals(username)) {
                    result.error500("手机号已存在!");
                    return result;
                }
            }
            if (StringUtils.isNotBlank(realname)) {
                sysUser.setRealname(realname);
            }
            if (StringUtils.isNotBlank(avatar)) {
                sysUser.setAvatar(avatar);
            }
            if (StringUtils.isNotBlank(sex)) {
                sysUser.setSex(Integer.parseInt(sex));
            }
            if (StringUtils.isNotBlank(phone)) {
                sysUser.setPhone(phone);
            }
            if (StringUtils.isNotBlank(email)) {
                sysUser.setEmail(email);
            }
            if (null != birthday) {
                sysUser.setBirthday(birthday);
            }
            sysUser.setUpdateTime(new Date());
            sysUserService.updateById(sysUser);
        }

        return result;
    }

    /**
     * 移动端保存设备信息
     *
     * @param clientId
     * @return
     */
    @RequestMapping(value = "/saveClientId", method = RequestMethod.GET)
    public Result<SysUsers> saveClientId(HttpServletRequest request, @RequestParam("clientId") String clientId) {
        Result<SysUsers> result = new Result<SysUsers>();

        String username = JwtUtil.getUserNameByToken(request);
        SysUsers sysUser = sysUserService.getUserByName(username);
        if (sysUser == null) {
            result.error500("未找到对应用户!");
        } else {
            sysUser.setClientId(clientId);
            sysUserService.updateById(sysUser);
        }

        return result;
    }

    /**
     * 根据userid获取用户信息和部门员工信息
     *
     * @return Result
     */
    @GetMapping("/queryChildrenByUsername")
    public Result queryChildrenByUsername(@RequestParam("userId") String userId) {
        //获取用户信息
        Map<String, Object> map = new HashMap<String, Object>();
        SysUsers sysUser = sysUserService.getById(userId);
        String username = sysUser.getUsername();
        Integer identity = sysUser.getUserIdentity();
        map.put("sysUser", sysUser);
        if (identity != null && identity == 2) {
            //获取部门用户信息
            String departIds = sysUser.getDepartIds();
            if (StringUtils.isNotBlank(departIds)) {
                List<String> departIdList = Arrays.asList(departIds.split(","));
                List<SysUsers> childrenUser = sysUserService.queryByDepIds(departIdList, username);
                map.put("children", childrenUser);
            }
        }
        return Result.ok(map);
    }

    /**
     * 移动端查询部门用户信息
     *
     * @param departId
     * @return
     */
    @GetMapping("/appQueryByDepartId")
    public Result<List<SysUsers>> appQueryByDepartId(@RequestParam(name = "departId", required = false) String departId) {
        Result<List<SysUsers>> result = new Result<List<SysUsers>>();
        List<String> list = new ArrayList<String>();
        list.add(departId);
        List<SysUsers> childrenUser = sysUserService.queryByDepIds(list, null);
        result.setResult(childrenUser);
        return result;
    }

    /**
     * 移动端查询用户信息(通过用户名模糊查询)
     *
     * @param keyword
     * @return
     */
    @GetMapping("/appQueryUser")
    public Result<List<SysUsers>> appQueryUser(@RequestParam(name = "keyword", required = false) String keyword) {
        Result<List<SysUsers>> result = new Result<List<SysUsers>>();
        LambdaQueryWrapper<SysUsers> queryWrapper = new LambdaQueryWrapper<SysUsers>();
        //TODO 外部模拟登陆临时账号，列表不显示
        queryWrapper.ne(SysUsers::getUsername, "_reserve_user_external");
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(i -> i.like(SysUsers::getUsername, keyword).or().like(SysUsers::getRealname, keyword));
        }
        List<SysUsers> list = sysUserService.list(queryWrapper);
        //批量查询用户的所属部门
        //step.1 先拿到全部的 useids
        //step.2 通过 useids，一次性查询用户的所属部门名字
        List<String> userIds = list.stream().map(SysUsers::getId).collect(Collectors.toList());
        if (userIds != null && userIds.size() > 0) {
            Map<String, String> useDepNames = sysUserService.getDepNamesByUserIds(userIds);
            list.forEach(item -> {
                item.setOrgCodeTxt(useDepNames.get(item.getId()));
            });
        }
        result.setResult(list);
        return result;
    }

    /**
     * 根据用户名修改手机号
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/updateMobile", method = RequestMethod.PUT)
    public Result<?> changMobile(@RequestBody JSONObject json, HttpServletRequest request) {
        String smscode = json.getString("smscode");
        String phone = json.getString("phone");
        Result<SysUsers> result = new Result<SysUsers>();
        //获取登录用户名
        String username = JwtUtil.getUserNameByToken(request);
        if (oConvertUtils.isEmpty(username) || oConvertUtils.isEmpty(smscode) || oConvertUtils.isEmpty(phone)) {
            result.setMessage("修改手机号失败！");
            result.setSuccess(false);
            return result;
        }
        Object object = redisUtil.get(phone);
        if (null == object) {
            result.setMessage("短信验证码失效！");
            result.setSuccess(false);
            return result;
        }
        if (!smscode.equals(object)) {
            result.setMessage("短信验证码不匹配！");
            result.setSuccess(false);
            return result;
        }
        SysUsers user = sysUserService.getUserByName(username);
        if (user == null) {
            return Result.error("用户不存在！");
        }
        user.setPhone(phone);
        sysUserService.updateById(user);
        return Result.ok("手机号设置成功!");
    }

    /**
     * 获取用户
     *
     * @return
     */
    @GetMapping("/users")
    public Result<?> getUsers() {
        List<SysUsers> userList = sysUserService.getList();
        List<Map<String, String>> returnList = new ArrayList<>(userList.size());
        userList.forEach(e -> {
            Map<String, String> map = new HashMap<>(2);
            map.put("value", e.getUsername());
            map.put("label", e.getRealname());
            returnList.add(map);
        });
        return Result.ok(returnList);
    }


    /**
     * 修改用户身份证
     *
     * @return
     */

    @RequestMapping(value = "/updateUserCard")
    public Result updateUserCard(String cardId) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUsers sysUser = new SysUsers();
        sysUser.setId(loginUser.getId());
        sysUser.setCardId(cardId);
        sysUserService.updateById(sysUser);
        return Result.ok("修改成功");
    }


    /**
     * 修改用户身份证
     *
     * @return
     */

    @RequestMapping(value = "/findUserId")
    public Result updateUserCard() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUsers byId = sysUserService.getById(loginUser.getId());
        return Result.ok(byId.getCardId());
    }

    @GetMapping("/getUserInfoByCondition")
    public Result<?> getUserInfoByCondition(SysUsers sysUser) {
        IPage<SysUsers> usePage = sysUserService.getUsersWithDeptIds(new Page<>(0, 1), sysUser);
        if (usePage != null && CollUtil.isNotEmpty(usePage.getRecords())) {
            sysUser = usePage.getRecords().get(0);
            if (StringUtils.isNotEmpty(sysUser.getOrgCodeTxt())) {
                List<String> deptIds = Arrays.asList(sysUser.getOrgCodeTxt().split(","));
                sysUser.setAllocateOrgList(sysDepartService.list(new QueryWrapper<SysDepart>().in("id", deptIds)));
            }
            List<JSONObject> roleList = sysBaseAPI.getRoleByUsername(sysUser.getUsername());
            if (CollUtil.isNotEmpty(roleList)) {
                sysUser.setRoleName(roleList.stream().map(item -> item.getString("roleName")).collect(Collectors.joining(",")));
                sysUser.setRoleCodes(roleList.stream().map(item -> item.getString("roleCode")).collect(Collectors.joining(",")));
            }
        }
        return Result.OK(sysUser);

    }

    /**
     * 获取个人中心的用户的信息
     *
     * @return
     */
    @GetMapping("/getInfo")
    public Result<?> getInfo() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUsers sysUser = sysUserService.getById(loginUser.getId());
        List<JSONObject> roleList = sysBaseAPI.getRoleByUsername(sysUser.getUsername());
        if (CollUtil.isNotEmpty(roleList)) {
            sysUser.setRoleName(roleList.stream().map(item -> item.getString("roleName")).collect(Collectors.joining(",")));
            sysUser.setRoleCodes(roleList.stream().map(item -> item.getString("roleCode")).collect(Collectors.joining(",")));
        }
        return Result.OK(sysUser);

    }

    @RequestMapping("/updateUserInfo")
    public Result<?> updateUserInfo(@RequestBody LoginUser loginUser) {
        SysUsers user = new SysUsers();
        user.setId(loginUser.getId());
        user.setUsername(loginUser.getUsername());
        user.setPhone(loginUser.getPhone());
        user.setTelephone(loginUser.getTelephone());
        user.setEmail(loginUser.getEmail());
        user.setCreateTime(loginUser.getCreateTime());
        user.setRealname(loginUser.getRealname());
        user.setSex(loginUser.getSex());
        user.setAvatar(loginUser.getAvatar());
        sysUserService.updateById(user);
        return Result.OK("保存成功!");
    }


    @Autowired
    private SysDepartServiceImpl departService;

    /**
     * 郑大用户同步
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/receive", method = RequestMethod.POST)
    @ResponseBody
    public String receive(String request) throws DocumentException, ParseException {
        //解析signatureContent信息
        log.info("收到了消息，内容是：" + request); // request就是xml数据
        Document document = DocumentHelper.parseText(request);
        Element root = document.getRootElement();
        Element identityticket = root.element("signatureContent");
        String signatureContent = Base64Util.decode(identityticket.getStringValue());

        log.info("解析signatureContent信息得到的xml:" + signatureContent);
        Document document1 = DocumentHelper.parseText(signatureContent);
        Element rootElement = document1.getRootElement();
        String content = rootElement.element("content").getStringValue();

        log.info("解析content信息得到的xml:" + content);
        //用户信息
        Document userxml = DocumentHelper.parseText(content);

        ArrayList<SysDepart> sysDepartsNoPid = new ArrayList<>();
        ArrayList<SysDepart> sysDepartsPid = new ArrayList<>();

        Element userxmlRootElement = userxml.getRootElement();
        List<Element> resource = userxmlRootElement.elements("resource");
        String result = null;
        String type = null;
        for (Element element : resource) {

            type = element.attributeValue("type");
            if (type.equals("User")) {//用户信息
                result = saveUser(element);
                if (!Objects.equals(result, "保存用户成功!")) {
                    String xml3 = result(result);
                    return xml3;
                }

            } else if (type.equals("Organization")) {//部门信息
                SysDepart sysDepart = new SysDepart();
                String deptId = element.attributeValue("no");
                sysDepart.setId(deptId);
                String deptName = element.element("name").getStringValue();
                sysDepart.setDepartName(deptName);
                List<Element> elements = element.element("properties").elements("property");
                for (Element depes : elements) {
                    String oid = depes.attributeValue("oid");
                    switch (oid) {
                        case "1.2.156.10197.6.1.2.301.2.106":
                            String pid = depes.attributeValue("value");
                            if (StringUtils.isBlank(pid)) {
                                sysDepart.setParentId("");
                                sysDepart.setOrgType("1");
                            } else {
                                sysDepart.setParentId(pid);
                                sysDepart.setOrgType("2");
                            }
                            break;
                        case "1.2.156.10197.6.1.2.301.2.81":
                            String order = depes.attributeValue("value");
                            sysDepart.setDepartOrder(Integer.valueOf(order));
                    }
                }

                if (StringUtils.isBlank(sysDepart.getParentId())) {
                    sysDepartsNoPid.add(sysDepart);
                } else {
                    sysDepartsPid.add(sysDepart);
                }
            }
        }
        if (type.equals("Organization")) {
            result = saveDeptInfo(sysDepartsNoPid, sysDepartsPid);
            if (!Objects.equals(result, "保存部门成功!")) {
                String xml3 = result(result);
                return xml3;
            }
        }


        String xml3 = result(result);
        return xml3;
    }

    private String result(String result) {
        String start = "";
        String massage = "";
        if (result == "保存部门成功!" || result == "保存用户成功!") {
            start = "0";

        } else {
            start = "1";
            massage = result;
        }
        String xml1 = "<result><status>" + start + "</status><failReason>" + massage + "</failReason></result>";
        String uuid = UUID.randomUUID().toString();
        String xml2 = "<?xml version=1.0 encoding=utf-8?><signatureContent><nonce>" + uuid + "</nonce><content>" + xml1 + "</content></signatureContent>";
        String encode = Base64Util.encode(xml2);
        return "<?xml version=1.0 encoding=utf-8 ?><envelope version=1.0><type>0</type><signAlgOid></signAlgOid><signature></ signature><signatureContent>" + encode + "</signatureContent></envelope>";
    }

    private String saveDeptInfo(ArrayList<SysDepart> sysDepartsNoPid, ArrayList<SysDepart> sysDepartsPid) {
        for (SysDepart sysDepart : sysDepartsNoPid) {
            SysDepart depart = sysDepartService.getById(sysDepart.getId());
            if (depart == null) { // 新增
                boolean res = departService.saveDepartUk(sysDepart);
                if (!res) {
                    return sysDepart.getDepartName() + "根部门保存失败!";
                }
            } else { //修改
                Boolean res = departService.updateDepartDataByIdUk(sysDepart);
                if (!res) {
                    return sysDepart.getDepartName() + "修改根部门失败!";
                }
            }
        }
        String sysDepart = save(sysDepartsPid);
        if (!Objects.equals(sysDepart, "保存部门成功!")) {
            return sysDepart;
        }
        return "保存部门成功!";
    }

    private String save(ArrayList<SysDepart> sysDepartsPid) {
        ArrayList<SysDepart> sysDeparts = new ArrayList<>();
        for (SysDepart sysDepart : sysDepartsPid) {
            SysDepart depart = sysDepartService.getById(sysDepart.getId());
            if (null == depart) {
                if (sysDepartService.getById(sysDepart.getParentId()) != null) {
                    boolean res = departService.saveDepartUk(sysDepart);
                    if (!res) {
                        return sysDepart.getDepartName() + "节点部门保存失败!";
                    }
                } else {
                    sysDeparts.add(sysDepart);
                }
            } else {
                Boolean res = departService.updateDepartDataByIdUk(sysDepart);
                if (!res) {
                    return sysDepart.getDepartName() + "修改根部门失败!";
                }
            }
        }
        if (sysDeparts.size() != 0) {
            return save(sysDeparts);
        } else {
            return "保存部门成功!";
        }
    }


    private String saveUser(Element element) throws ParseException {
        SysUsers users = new SysUsers();
        users.setDelFlag(0);

        SysUserDepart sysUserDepart = new SysUserDepart();
        String userId = element.attributeValue("no");
        users.setId(userId);
        String userName = element.element("name").getStringValue();
        users.setRealname(userName);
        users.setPassword("password");//默认设置密码;
        users.setUsername(userName);
        Integer status = Integer.valueOf(element.element("status").getStringValue());//0-在用，1-停用，2-销毁
        if (status == 0) {
            users.setStatus(1);
        } else {
            users.setStatus(2);
        }
        List<Element> elements = element.element("properties").elements("property");
        for (Element user : elements) {
            String oid = user.attributeValue("oid");
            switch (oid) {
                case "1.2.156.10197.6.1.2.301.2.4":
                    String sex = user.attributeValue("value");
                    if (sex.equals("男")) {
                        users.setSex(1);
                    } else {
                        users.setSex(2);
                    }
                    break;
                case "1.2.156.10197.6.1.2.301.2.12":
                    String birthday = user.attributeValue("value");
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date parse = format.parse(birthday);
                    users.setBirthday(parse);
                    break;
                case "1.2.156.10197.6.1.2.301.2.107":
                    String dept = user.attributeValue("value");
                    sysUserDepart.setUserId(userId);
                    sysUserDepart.setDepId(dept);
//                            sysUserDepartService.save();
                    break;
            }
        }
        SysUsers sysUsers = sysUserService.getByUId(userId);
        if (null != sysUsers) {
            boolean b = sysUserService.updateById(users);
            if (!b) {
                return users.getRealname() + "更新用户失败!";
            }
            if (sysUserDepart.getUserId() == null || sysUserDepart.getDepId() == null) {
                return users.getRealname() + "更新部门关系失败,数据有空";
            }
            boolean res = sysUserDepartService.updateByUId(userId, sysUserDepart);
            if (!res) {
                return users.getRealname() + "更新部门关系失败!";
            }
        } else {
            boolean save = sysUserService.save(users);
            if (!save) {
                return users.getRealname() + "保存用户失败!";
            }
            if (sysUserDepart.getUserId() == null || sysUserDepart.getDepId() == null) {
                return users.getRealname() + "保存部门关系失败,数据有空";
            }
            boolean save1 = sysUserDepartService.save(sysUserDepart);
            if (!save1) {
                return users.getRealname() + "保存部门关系失败";
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            SysRole role = roleService.getOne(new QueryWrapper<SysRole>().eq("role_code", "UkeyRole"));
            if (null == role) {
                return users.getRealname() + "角色授权失败!";
            }
            sysUserRole.setRoleId(role.getId());
            sysUserRoleService.save(sysUserRole);
        }
        return "保存用户成功!";
    }

    /**
     * 根据对象里面的属性值作in查询 属性可能会变 用户组件用到
     *
     * @param sysUser
     * @return
     */
    @GetMapping("/getMultiUser")
    public List<SysUsers> getMultiUser(SysUsers sysUser) {
        QueryWrapper<SysUsers> queryWrapper = QueryGenerator.initQueryWrapper(sysUser, null);
        //update-begin---author:wangshuai ---date:20220104  for：[JTC-297]已冻结用户仍可设置为代理人------------
        queryWrapper.eq("status", Integer.parseInt(CommonConstant.STATUS_1));
        //update-end---author:wangshuai ---date:20220104  for：[JTC-297]已冻结用户仍可设置为代理人------------
        List<SysUsers> ls = this.sysUserService.list(queryWrapper);
        for (SysUsers user : ls) {
            user.setPassword(null);
            user.setSalt(null);
        }
        return ls;
    }

    @RequestMapping(value = "/getThreePowers")
    public Object isThreePowers() {
        //    @Value(value = "${insight.isThreePowers}")
        JSONObject result = new JSONObject();
        String threePowersKey = com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        int isThreePowers = Integer.parseInt(String.valueOf(cacheUtils.getValueByKey(threePowersKey + "_isEnable")));
        boolean roleShow = false;
        List<String> singleRole = new ArrayList<>();
        List<String> threePowers = new ArrayList<>();
        if (isThreePowers == 1) {
            singleRole = singleRole();
            threePowers.addAll(singleRole);
            threePowers.addAll(getUserRoot());
            threePowers.add(CommonConstant.ADMIN);
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            if (getUserSecadm().contains(loginUser.getUsername()) || CommonConstant.ADMIN.equals(loginUser.getUsername())) {
                roleShow = true;
            }

        }
        result.put("isThreePowers", isThreePowers);
        result.put("roleShow", roleShow);
        result.put("threePowers", threePowers);
        result.put("singleRole", singleRole);
        return Result.OK(result);
    }

    @GetMapping("/threePowers")
    public Result<Object> threePowers() {
        return Result.OK(getThreePowers());
    }

    @GetMapping("/getCurrentUser")
    public Result<Object> getCurrentUser() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return Result.OK(loginUser);
    }

    public static List<String> getThreePowers() {
        List<String> threePowers = singleRole();
        threePowers.addAll(getUserRoot());
        threePowers.add(CommonConstant.ADMIN);
        return threePowers;
    }

    private static List<String> singleRole() {
        List<String> list = new ArrayList<>();
        list.addAll(getUserSecadm());
        list.addAll(getUserAuditadm());
        return list;
    }

    private static List<String> getUserRoot() {
        String threePowersKey = com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        String userRoot = String.valueOf(cacheUtils.getValueByKey((threePowersKey + "_userRoot")));
        return new ArrayList<>(Arrays.asList(userRoot.split(",")));
    }

    private static List<String> getUserSecadm() {
        String threePowersKey = com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        String userSecadm = String.valueOf(cacheUtils.getValueByKey((threePowersKey + "_userSecadm")));
        return new ArrayList<>(Arrays.asList(userSecadm.split(",")));
    }

    private static List<String> getUserAuditadm() {
        String threePowersKey = com.yuanqiao.insight.common.constant.CommonConstant.DATA_DICT_KEY + "insight_threePowers";
        String userAuditadm = String.valueOf(cacheUtils.getValueByKey((threePowersKey + "_userAuditadm")));
        return new ArrayList<>(Arrays.asList(userAuditadm.split(",")));
    }
}
